package com.cnap.model.image;

import cn.hutool.crypto.SecureUtil;
import com.cnap.config.DockerConfig;
import com.cnap.model.image.config.ConfigInfo;
import com.cnap.service.ProgressService;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.TagImageCmd;
import com.github.dockerjava.api.model.AuthConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.function.BooleanSupplier;

/**
 * 镜像操作任务类
 *
 * @author xc
 **/
public class ImageProcessTask implements BooleanSupplier {
    private static final Logger LOGGER = LoggerFactory.getLogger(ImageProcessTask.class);

    private final String unzipFile;
    private final String parentId;
    private final ProgressService progressService;
    private final DockerConfig dockerConfig;
    private final ConfigInfo configInfo;
    private final File imageFile;
    private final String userName;

    public ImageProcessTask(String unzipFile, String parentId, ProgressService progressService,
                            DockerConfig dockerConfig, ConfigInfo configInfo, File imageFile, String userName) {
        this.unzipFile = unzipFile;
        this.parentId = parentId;
        this.progressService = progressService;
        this.dockerConfig = dockerConfig;
        this.configInfo = configInfo;
        this.imageFile = imageFile;
        this.userName = userName;
    }

    @Override
    public boolean getAsBoolean() {
        return call();
    }

    /*
        镜像推送依赖docker
        需要将宿主机的docker进程挂载至容器内
        或者开启docker的远程访问
        但远程访问的docker进程容易卡死
        所以推荐直接挂载宿主机的docker进程
     */

    /**
     * 镜像处理
     *
     * @return 结果
     */
    public Boolean call() {
        DockerClient dockerClient = dockerConfig.getDockerClient();
        try {
            // 读取镜像文件并推送
            // 1. load镜像
            String imageFullName = configInfo.getConfigImageInfo().getImageName();
            String imagesNameWithoutRep = imageFullName.substring(imageFullName.lastIndexOf("/") + 1,
                    imageFullName.indexOf(":"));
            String imageTag = imageFullName.substring(imageFullName.lastIndexOf(":") + 1);
            dockerClient.loadImageCmd(new FileInputStream(imageFile)).exec();
            LOGGER.info("load image: {} success", imageFullName);
            // 2. 重新打tag
            String imageNameWithRegistry = dockerConfig.getRegistryPrefix() + getMd5StringWith8(userName) + "/" + imagesNameWithoutRep;
            // 不改变实际tag

            TagImageCmd tagImageCmd = dockerClient.tagImageCmd(imageFullName, imageNameWithRegistry, imageTag);
            tagImageCmd.exec();
            LOGGER.info("reTag image {} to {} success", imagesNameWithoutRep, imageNameWithRegistry);
            // 3. 推送到harbor
            String newImageNameWithTag = imageNameWithRegistry + ":" + imageTag;
            dockerClient.pushImageCmd(newImageNameWithTag).withTag(imageTag).withAuthConfig(getAuthConfig()).start().awaitCompletion();

            // 成功推送后删除本地load镜像
            dockerClient.removeImageCmd(newImageNameWithTag).exec();
            LOGGER.info("delete local image: {}", newImageNameWithTag);
            dockerClient.removeImageCmd(imageFullName).exec();
            LOGGER.info("delete local image: {}", imageFullName);
            LOGGER.info("finish image process, {}", imageFullName);
        } catch (IOException e) {
            LOGGER.error("can't read image file, current file={}", unzipFile);
            progressService.updateProgressException(parentId, "压缩文件内没有找到镜像文件");
            return false;
        } catch (InterruptedException e) {
            LOGGER.error("push image fail, error:{}", e.getMessage());
            progressService.updateProgressException(parentId, "推送镜像失败");
            Thread.currentThread().interrupt();
            return false;
        }
        return true;
    }

    private AuthConfig getAuthConfig() {
        return new AuthConfig()
                .withUsername(dockerConfig.getRegistryUserName())
                .withPassword(dockerConfig.getRegistryPassword())
                .withRegistryAddress(dockerConfig.getRegistryUrl());
    }

    /**
     * 获取userName哈希过后的前8位字符
     *
     * @param userName 用户名
     * @return 结果
     */
    private String getMd5StringWith8(String userName) {
        String md5 = SecureUtil.md5(userName);
        return md5.substring(0, 8);
    }
}
